package 力扣;

import java.util.Arrays;

/**
 中序遍历 inorder = [9,3,15,20,7]  左根右
 后序遍历 postorder = [9,15,7,20,3] 左右根
 返回如下的二叉树：

  3
 / \
 9  20
 /  \
 15   7
 */

public class _106从中序与后序遍历序列构造二叉树 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if( inorder == null || postorder ==null ) return null;
        if( inorder.length == 0 || postorder.length == 0 ) return null;
        if( inorder.length != postorder.length) return null;
        TreeNode treeNode = new TreeNode(postorder[postorder.length-1]); //构造根节点
        for (int i = 0; i < inorder.length; i++) {
            if (postorder[postorder.length-1] == inorder[i]){
                // left 都是 0~i
                treeNode.left = buildTree(Arrays.copyOfRange(inorder,0,i),Arrays.copyOfRange(postorder,0,i));
                // right 中序 从 i+1 开始 后序 从 i开始
                treeNode.right = buildTree(Arrays.copyOfRange(inorder,i+1,inorder.length),Arrays.copyOfRange(postorder,i,inorder.length-1));
            }
        }
        return treeNode;
    }
}
